<template>
  <VPage edit :footer="{ offset: 10 }">
    <div class="box">
      <el-card class="box-card box-card1">
        <div class="flex items-center">
          <FormTitle title="基础信息" style="width: 80px" />
          <span class="mb-[14px] status">{{ formData.plan_status_text }}</span>
        </div>

        <!-- <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="formData" :originOption="originOption"> </XForm>
        <div class="grid grid-cols-3">
          <VText title="部门当月采购额度" value="500.0W RMB" :line="1" />
          <VText title="已使用额度" value="120.0W RMB" :line="1" />
          <VText title="剩余额度（不包含本单）" value="380.0W RMB" :line="1" />
        </div> -->
        <BaseForm :formData="formData" :plan_id="router.currentRoute.value.params.id" @submit="queryDtl" />
      </el-card>

      <el-card class="box-card my-[8px] box-card2">
        <div>
          <div class="flex">
            <FormTitle title="商品信息" style="margin-bottom: 0px; width: 100px" />
            <div v-if="pageName != 'PurchasePlanStockUpPlanCreate'">
              <VButton type="primary" icon="Plus" @click="openAddGoodsRef">添加商品</VButton>
              <VButton type="primary" icon="Plus" @click="onAudit()">审 核</VButton>
              <VButton type="primary" icon="Plus" @click="onUpdate">变 更</VButton>
              <VButton type="danger" icon="WarningFilled" @click="onDelete()">删除</VButton>
            </div>
          </div>
          <div class="my-[14px] flex items-center">
            <el-tabs v-model="activeName" class="tabs" @tab-click="tabHandleClick">
              <el-tab-pane v-for="item in formData.details" :key="item.key" :name="item.reviews_status" :label="`${item.reviews_status_text} (${item.count})`"></el-tab-pane>
            </el-tabs>
            <!-- {{ totalAmount }} -->
            <div class="ml-[16px]">汇总金额：{{ formData.stocking_amount }} RMB</div>

            <!-- <VButton icon="Download" type="" class="ml-auto" @click="onImport">导入</VButton> -->
          </div>
        </div>
        <div class="bbb">
          <vxe-grid v-bind="tableOptins" ref="tableRef" height="auto" />
        </div>
      </el-card>
    </div>

    <template #footer>
      <el-button :disabled="loading" @click="handleCancel">返回</el-button>
    </template>
  </VPage>
  <!-- 日志 -->
  <XLog ref="logRef" :api="planSpaLog"></XLog>

  <!-- 添加商品弹窗 -->
  <DialogAddGoods ref="DialogAddGoodsRef" @submit="submitAddGoodsRef" :originOption="originOption" />

  <!-- 弹窗 表单编辑 -->
  <ConfirmInput v-model="batchVisible" v-bind="currentConfirm" @submit="handleConfirmSubmit" />

  <!-- ASIN销量趋势 -->
  <AsinSalesTrend ref="AsinSalesTrendRef" />

  <!-- 新增变更单 -->
  <!-- <Details ref="DetailsUpdateRef" /> -->
</template>

<script setup lang="jsx" name="view,edit">
// ASIN销量趋势
import AsinSalesTrend from "@/views/plan/components/AsinSalesTrend/index.vue"
const AsinSalesTrendRef = ref()

import BaseForm from "./baseForm.vue"

// 新增变更单
// import Details from "@/views/plan/stockUpPlanUpdate/components/details/index.vue"
// const DetailsUpdateRef = ref()
import action from "@/utils/action.js"
// 变更
const onUpdate = () => {
  let arr = getSelectRow()
  if (arr.length != 1) {
    return
  }
  if (arr?.[0].review_status != 6) {
    return ElMessage({ showClose: true, message: "已审核状态才可以变更", type: "warning" })
  }
  purchaseDemandSkuDetail({ source_id: arr[0]?.id }).then((res) => {
    sessionStorage.setItem("PURCHASE_HANDLE", JSON.stringify({ pds_id: res.data.pds_id, demand_no: res.data.demand_no, sku: res.data.sku, sku_no: res.data.sku_no }))
    action.setGlobalState({
      changeMicoTabsPath: {
        path: "/purchase/demand/sku",
        type: "push",
      },
    })
  })
}

import {
  stockingPlanDetail,
  stockingPlanTotalAmount,
  planSpaReview,
  planSpaUpdateRemark,
  planSpaDelete,
  planSpaCreate,
  planSpaUpdateTransportationType,
  planSpaUpdateShipTime,
  planSpaLog,
  planSpaUpdateStockinQuantity,
  purchaseDemandSkuDetail,
  departmentAmountConfig,
} from "@/api/plan"
const router = useRouter()

const handleCancel = () => {
  action.setGlobalState({
    changeMicoTabsPath: {
      type: "closeActiveTab",
    },
  })
}

import {
  originOption, // 枚举
  stockUpPlanColumns, // 备货计划明细 列
  handleFunctions, // 操作
  currentConfirmOpt, // 表单编辑 弹窗配置
} from "./config.jsx"
// 操作
const handleFunction = ref({
  // 表格操作
  // 修改需求数量
  updateQuantity: (row) => {
    if ("5,6".includes(row.review_status)) {
      ElMessage({ showClose: true, message: "此状态不可修改", type: "warning" })
      return
    }
    planSpaUpdateStockinQuantity({
      id: row.id,
      stocking_quantity: row?.spa_analysis?.stocking_quantity,
      plan_id: router.currentRoute.value.params.id,
    }).then((res) => {
      queryDtl()
      ElMessage.success(res.message)

      // totalAmount.value = res.data.total_stocking_amount
    })
  },

  // 查看ASIN销量趋势
  openTendencyChart: (row) => {
    AsinSalesTrendRef.value.open(row.base_asin_id)
  },
  // 修改运输类型
  updateTransportation: (row) => {
    planSpaUpdateTransportationType({
      id: row.id,
      transportation_type: row.transportation_type,
    }).then((res) => {
      ElMessage.success(res.message)
    })
  },
  // 修改备注
  editRemark: (row) => {
    openConfirmInput("remark", row)
  },
  // 修改 预计发货时间
  shipTimeChange: (row) => {
    planSpaUpdateShipTime({ id: [row.id], estimated_shipping_time: row.estimated_shipping_time }).then((res) => {
      ElMessage.success(res.message)
    })
  },
  // 批量修改 预计发货时间
  batchShipTimeChange: (e) => {
    if (e) {
      let data = formData.value.details.find((v) => v.reviews_status == activeName.value).list
      planSpaUpdateShipTime({ id: data.map((v) => v.id), estimated_shipping_time: e }).then((res) => {
        ElMessage.success(res.message)
        queryDtl()
      })
    }
  },
})

onActivated(() => {
  nextTick(() => {}).then(() => {
    // console.log("从新进入")
  })
})

const pageName = ref("")
onMounted(async () => {
  pageName.value = router.currentRoute.value.name
  getOption()
  nextTick(() => {
    // 操作
    handleFunctions.value = { ...handleFunctions.value, ...handleFunction.value }
  })
  await queryDtl()
  // getTotalAmount()
})

// function getLastDayOfMonth() {
//   const currentDate = new Date()
//   const year = currentDate.getFullYear()
//   const month = currentDate.getMonth() + 1 // 月份从0开始，需要加1
//   const lastDayOfMonth = new Date(year, month, 0).getDate()
//   return lastDayOfMonth
// }

import { enumGet, enumOptions } from "@/api"
import { getAloneEnum } from "@/utils/enumUtils"
// 获取下拉数据
const getOption = async () => {
  const { data } = await enumGet({ name: ["Base.BaseAsinList.IsRequiresStockingEnum", "Base.BaseAsinList.TransportationTypeEnum"] })
  originOption.value["Base.BaseAsinList.IsRequiresStockingEnum"] = data["Base.BaseAsinList.IsRequiresStockingEnum"]
  originOption.value["Base.BaseAsinList.TransportationTypeEnum"] = data["Base.BaseAsinList.TransportationTypeEnum"]
  originOption.value.amazonSite = (await getAloneEnum(["amazonSite"]))?.amazonSite
}
import { parseTime } from "@/utils/ruoyi"
const queryDtl = async () => {
  let { id } = router.currentRoute.value.params
  let res = await stockingPlanDetail({ id })
  res.data.planning_department = Number(res.data.planning_department)

  res.data.details.forEach((val) => {
    val?.list?.forEach((v) => {
      v.spa_lt_days = v.spa_lt_days || {}
      v.spa_analysis = v.spa_analysis || {}
      v.spa_inventory_availability = v.spa_inventory_availability || {}
      v.spa_inventory = v.spa_inventory || {}
      v.spa_sales = v.spa_sales || {}
    })
  })

  formData.value = res.data
  let configParams = {
    department_id: [res.data.planning_department],
    month: parseTime(new Date(), "{y}-{m}"),
  }

  let AmountConfig = (await departmentAmountConfig(configParams))?.data?.[0]
  if (AmountConfig) {
    AmountConfig.employ_amount = AmountConfig.amount - AmountConfig.leave_amount
    formData.value = { ...formData.value, ...AmountConfig }
  }

  // 渲染表格数据
  tabHandleClick()
}

// import { organizationList, overallOptions } from '@/api/public'
// import { queryList, oplog, getFreeType, setStatus } from './api'
import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, ref, toRefs } from "vue"
// import {basicSetupAuthList} from '@/Auth/basic-setup.js'

// import Details from "./components/details/index.vue"
import XForm from "@/components/XForm/index.vue"
import FormTitle from "@/components/XForm/FormTitle.vue"
import ConfirmInput from "@/components/ConfirmInput/index.vue"
// 日志
import XLog from "@/components/XLog"
const logRef = ref()

const DetailsRef = ref()
const onImport = () => {}

const tableRef = ref()
const activeName = ref(0)
// 汇总金额
// const totalAmount = ref(0)
// 计算汇总金额
// const getTotalAmount = () => {
//   nextTick(() => {
//     stockingPlanTotalAmount({ pr_number: formData.value.pr_number }).then((res) => {
//       totalAmount.value = res.data.total_amount
//     })
//   })
// }
const tabHandleClick = (tab, event) => {
  nextTick(() => {
    let data = formData.value.details.find((v) => v.reviews_status == activeName.value).list
    tableRef.value.loadData(data)
  })
}

// 添加商品弹窗
import DialogAddGoods from "../components/DialogAddGoods.vue"
const DialogAddGoodsRef = ref()
// 添加商品 弹窗
const openAddGoodsRef = () => {
  DialogAddGoodsRef.value.open()
}
// 添加商品 保存
const submitAddGoodsRef = (value) => {
  let params = {
    plan_id: router.currentRoute.value.params.id,
    plan_spa: value.map((v) => ({ base_asin_id: v.id, stocking_quantity: 0 })),
  }
  planSpaCreate(params).then((res) => {
    queryDtl()
  })
}

const data = reactive({
  title: "详情",
  formData: {},
  loading: false,

  batchVisible: false,
  currentConfirm: {},
})
const { title, formData, loading, batchVisible, currentConfirm } = toRefs(data)

// 删除
const onDelete = (row = null) => {
  let arr = []
  if (row) {
    arr = [row]
  } else {
    arr = getSelectRow()
    if (!arr.length) {
      return false
    }
  }
  ElMessageBox.confirm(`此操作将删除 ${arr.length}条数据, 是否继续?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "oms-message-confirm-button",
  }).then(async () => {
    try {
      planSpaDelete({ id: arr.map((v) => v.id) }).then((res) => {
        ElMessage.success(res.message)
        queryDtl()
      })
    } catch (e) {
      throw Error(e)
    }
  })
}
// 审核
const onAudit = (row = null) => {
  let params = { ids: [] }
  let arr = []
  if (row) {
    params.ids = [row.id]
    params.review_status = row.review_status
  } else {
    let arr = getSelectRow()
    if (!arr.length) return
    let status = [...new Set(arr.map((v) => v.review_status))]
    if (status.length > 1) {
      ElMessage({ showClose: true, message: "只能审核同一状态数据", type: "warning" })
      return
    }
    if (!"1,2,3,4".includes(status[0])) {
      ElMessage({ showClose: true, message: "状态不可审核", type: "warning" })
      return
    }
    params.review_status = status[0]
    params.ids = arr.map((v) => v.id)
  }
  openConfirmInput("audit", params)
}

// 开启 弹窗 表单编辑
const openConfirmInput = (type, param) => {
  let confirm = {}
  console.log(param)
  switch (type) {
    case "audit": // 审核
      confirm = currentConfirmOpt.audit
      confirm.form = { id: param.ids }

      let confirmOriginOption = {
        review_type: originOption.value.review_type[param.review_status],
      }
      confirm.originOption = confirmOriginOption
      break
    case "remark": // 备注
      confirm = currentConfirmOpt.remark
      confirm.form = { id: param.id, remark: param.remark }
      break
  }
  confirm.type = type
  currentConfirm.value = confirm
  batchVisible.value = true
}
// 保存 弹窗 表单编辑
const handleConfirmSubmit = async (param) => {
  console.log(param)
  let requests = null
  switch (currentConfirm.value.type) {
    case "audit": // 审核
      requests = planSpaReview
      break
    case "remark": // 备注
      requests = planSpaUpdateRemark
      break
  }
  requests(param).then((res) => {
    ElMessage.success(res.message)
    batchVisible.value = false
    queryDtl()
    nextTick(() => {
      currentConfirm.value = {}
    })
  })
}

// 获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请选择一条数据进行操作", type: "warning" })
    return false
  }
  return getCheckboxRecords
}

const formOption = ref({ inline: true, labelWidth: "180px" })

const publicStyle = { style: { width: "100%" } }
const fieldList = ref([
  { label: "计划名称", field: "plan_name", ...publicStyle },
  { label: "PR单", field: "pr_number", ...publicStyle },
  { label: "备货类型", field: "plan_type_text", ...publicStyle },
  {
    label: "运营部门",
    field: "planning_department",
    type: "cascader",
    cascaderType: "department",
    placeholder: "运营部门",
    itemProps: {
      props: {
        emitPath: false,
        label: "name",
        value: "id",
        children: "sub",
      },
    },
    ...publicStyle,
  },
  { label: "状态", field: "plan_status_text", ...publicStyle },
  { label: "备注", field: "remarks", ...publicStyle },

  { label: "部门当月采购额度", field: "remarks", ...publicStyle },

  { label: "已使用额度", field: "remarks", ...publicStyle },

  { label: "剩余额度（不包含本单）", field: "remarks", ...publicStyle },

  // <VText title="部门当月采购额度" value="500.0W RMB" :line="1" />
  // <VText title="已使用额度" value="120.0W RMB" :line="1" />
  // <VText title="剩余额度（不包含本单）" value="380.0W RMB" :line="1" />
])

// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      fee_type: "",
      timeData: { type: "timeData", value: "" },
    },
  },
  rowConfig: { height: "160" },
  columns: [
    { type: "checkbox", fixed: "left", width: 60 },

    {
      title: "操作",
      width: 200,
      fixed: "right",
      slots: {
        default: ({ row, rowIndex }) => {
          return [
            <div>
              <el-button link type="primary" onClick={() => onAudit(row)}>
                审核
              </el-button>
              <el-button link type="primary" onClick={() => logRef?.value.open({ spa_id: row.id })}>
                日志
              </el-button>

              <el-button link type="danger" onClick={() => onDelete(row)}>
                删除
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  data: [],
})
tableOptins.columns.unshift(...stockUpPlanColumns.filter((v) => v.title != "备货计划信息"))
</script>
<style lang="scss" scoped>
:deep(.tabs) {
  margin-top: 0 !important;
  .el-tabs__header {
    margin-bottom: 0;
  }
}
.box {
  display: flex;
  flex-direction: column;
  height: calc(100% - 50px);
  .box-card1 {
  }
  .box-card2 {
    flex: 1;
    :deep(.el-card__body) {
      display: flex;
      flex-direction: column;
      height: 100%;
      padding-bottom: 10px !important;
      .bbb {
        flex: 1;
        overflow: hidden;
      }
    }
  }
}
.status {
  background: #faad14;
  border-radius: 4px 4px 4px 0px;
  color: #fff;
  font-size: 12px;
  padding: 1px 3px;
}
</style>
